"""
Phase 2: Trilemma Index Regressions
====================================
1. Z → each trilemma index (mi_index, ers_index, fo_index)
2. Three specifications: Z only, Z+controls, Z+controls+interactions
3. OECD/non-OECD subsample split
4. Direct dependency ratio decomposition (old_dep, youth_dep)
Hypothesis: aging → lower MI, higher ERS (pegging)
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys
import warnings
warnings.filterwarnings('ignore')

PROJECT_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = PROJECT_DIR.parent
sys.path.insert(0, str(ROOT_DIR / "multilateral" / "src"))
from model import PanelGLS

DATA = PROJECT_DIR / "data" / "processed"
OUT_TABLES = PROJECT_DIR / "output" / "tables"
OUT_TABLES.mkdir(parents=True, exist_ok=True)

# OECD members (as of 2024, 38 countries)
OECD = {
    'AUS', 'AUT', 'BEL', 'CAN', 'CHL', 'COL', 'CRI', 'CZE', 'DNK', 'EST',
    'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ISR', 'ITA', 'JPN',
    'KOR', 'LVA', 'LTU', 'LUX', 'MEX', 'NLD', 'NZL', 'NOR', 'POL', 'PRT',
    'SVK', 'SVN', 'ESP', 'SWE', 'CHE', 'TUR', 'GBR', 'USA',
}


def stars(p):
    if p < 0.01: return '***'
    if p < 0.05: return '**'
    if p < 0.1: return '*'
    return ''


def fmt(val, se, p):
    s = stars(p)
    return f"{val:.4f}{s}", f"({se:.4f})"


def run_panel_gls(df, y_var, x_vars, label):
    """Run PanelGLS and return results dict."""
    cols = [y_var] + x_vars + ['iso3', 'year']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    gls = PanelGLS()
    y = sub[y_var].values
    X = sub[x_vars].values
    try:
        gls.fit(y, X, sub['iso3'].values, sub['year'].values)
    except Exception as e:
        print(f"  {label}: GLS failed ({e}), skipping")
        return None

    result = {
        'model': label,
        'n_obs': gls.n_obs,
        'n_countries': gls.n_countries,
        'r_squared': gls.r_squared,
        'rho': gls.rho,
    }
    print(f"\n  {label} (N={gls.n_obs}, R²={gls.r_squared:.4f})")
    for i, name in enumerate(x_vars):
        sig = stars(gls.pvalues[i])
        print(f"    {name:30s} {gls.beta[i]:8.4f} ({gls.se[i]:.4f}) {sig}")
        result[f'{name}_coef'] = gls.beta[i]
        result[f'{name}_se'] = gls.se[i]
        result[f'{name}_p'] = gls.pvalues[i]

    return result


def write_table(results, filename, title):
    """Write regression results as markdown table."""
    if not results:
        return

    lines = [f"# {title}\n"]

    all_vars = []
    for r in results:
        for k in r:
            if k.endswith('_coef'):
                vname = k.replace('_coef', '')
                if vname not in all_vars:
                    all_vars.append(vname)

    model_labels = [r['model'] for r in results]
    header = "| Variable | " + " | ".join(model_labels) + " |"
    sep = "|:---|" + "|".join(["---:" for _ in results]) + "|"
    lines.append(header)
    lines.append(sep)

    for var in all_vars:
        coef_row = f"| {var} |"
        se_row = "| |"
        for r in results:
            if f'{var}_coef' in r:
                c, s = fmt(r[f'{var}_coef'], r[f'{var}_se'], r[f'{var}_p'])
                coef_row += f" {c} |"
                se_row += f" {s} |"
            else:
                coef_row += " |"
                se_row += " |"
        lines.append(coef_row)
        lines.append(se_row)

    lines.append("|:---|" + "|".join(["---:" for _ in results]) + "|")
    n_row = "| N |"
    r2_row = "| R² |"
    nc_row = "| Countries |"
    for r in results:
        n_row += f" {r['n_obs']} |"
        r2_row += f" {r['r_squared']:.4f} |"
        nc_row += f" {r['n_countries']} |"
    lines.append(n_row)
    lines.append(r2_row)
    lines.append(nc_row)

    lines.append("\n*Standard errors in parentheses.*")
    lines.append("*\\*p<0.1, \\*\\*p<0.05, \\*\\*\\*p<0.01*")

    path = OUT_TABLES / filename
    path.write_text('\n'.join(lines))
    print(f"\n  Saved: {path}")


# ── 1. Z → Trilemma Indices ──────────────────────────────────────────

def trilemma_index_regressions(df):
    """Z → mi_index, ers_index, fo_index with three specs each."""
    print("\n" + "=" * 60)
    print("1. Z → TRILEMMA INDEX REGRESSIONS")
    print("=" * 60)

    z_vars = ['Z_1', 'Z_2', 'Z_3']
    controls_full = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw', 'kaopen']
    # fo_index ≈ kaopen, so remove kaopen when fo_index is DV
    controls_no_kaopen = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw']

    # Create interaction terms
    df['Z_1_x_kaopen'] = df['Z_1'] * df['kaopen']
    df['Z_2_x_kaopen'] = df['Z_2'] * df['kaopen']
    df['Z_3_x_kaopen'] = df['Z_3'] * df['kaopen']

    trilemma_dvs = [
        ('mi_index', 'MI', controls_full),
        ('ers_index', 'ERS', controls_full),
        ('fo_index', 'FO', controls_no_kaopen),
    ]

    for dv, dv_label, controls in trilemma_dvs:
        print(f"\n  --- DV: {dv} ({dv_label}) ---")
        results = []

        # Spec 1: Z only
        r = run_panel_gls(df, dv, z_vars, f'{dv_label} (Z only)')
        if r: results.append(r)

        # Spec 2: Z + controls
        r = run_panel_gls(df, dv, z_vars + controls, f'{dv_label} (Z+ctrl)')
        if r: results.append(r)

        # Spec 3: Z + controls + Z×KAOPEN interactions
        # For fo_index, still include interactions (they test whether Z effect
        # varies with openness), but do NOT include kaopen as a level control
        interact_vars = ['Z_1_x_kaopen', 'Z_2_x_kaopen', 'Z_3_x_kaopen']
        r = run_panel_gls(df, dv, z_vars + controls + interact_vars,
                          f'{dv_label} (Z+ctrl+int)')
        if r: results.append(r)

        filename = f"trilemma_{dv_label.lower()}.md"
        write_table(results, filename,
                    f"Demographics → {dv_label} Index ({dv})")


# ── 2. OECD/Non-OECD Subsample Split ─────────────────────────────────

def oecd_subsample(df):
    """OECD vs. non-OECD subsample for Z+controls spec."""
    print("\n" + "=" * 60)
    print("2. OECD vs. NON-OECD SUBSAMPLE SPLIT")
    print("=" * 60)

    df['is_oecd'] = df['iso3'].isin(OECD).astype(int)
    oecd_df = df[df['is_oecd'] == 1].copy()
    non_oecd_df = df[df['is_oecd'] == 0].copy()

    print(f"  OECD: {oecd_df['iso3'].nunique()} countries, {len(oecd_df)} obs")
    print(f"  Non-OECD: {non_oecd_df['iso3'].nunique()} countries, {len(non_oecd_df)} obs")

    z_vars = ['Z_1', 'Z_2', 'Z_3']
    controls_full = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw', 'kaopen']
    controls_no_kaopen = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw']

    results = []

    trilemma_dvs = [
        ('mi_index', 'MI', controls_full),
        ('ers_index', 'ERS', controls_full),
        ('fo_index', 'FO', controls_no_kaopen),
    ]

    for dv, dv_label, controls in trilemma_dvs:
        for sub_df, sub_label in [(oecd_df, 'OECD'), (non_oecd_df, 'Non-OECD')]:
            r = run_panel_gls(sub_df, dv, z_vars + controls,
                              f'{dv_label} ({sub_label})')
            if r: results.append(r)

    write_table(results, "trilemma_oecd_split.md",
                "Trilemma Index Regressions: OECD vs. Non-OECD")


# ── 3. Age Decomposition ─────────────────────────────────────────────

def age_decomposition(df):
    """Direct dependency ratios → trilemma indices."""
    print("\n" + "=" * 60)
    print("3. AGE DECOMPOSITION (old_dep, youth_dep)")
    print("=" * 60)

    age_vars = ['old_dep', 'youth_dep']
    controls_full = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw', 'kaopen']
    controls_no_kaopen = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'log_rel_opw']

    results = []

    trilemma_dvs = [
        ('mi_index', 'MI', controls_full),
        ('ers_index', 'ERS', controls_full),
        ('fo_index', 'FO', controls_no_kaopen),
    ]

    for dv, dv_label, controls in trilemma_dvs:
        r = run_panel_gls(df, dv, age_vars + controls,
                          f'{dv_label} (Age)')
        if r: results.append(r)

    write_table(results, "trilemma_age_decomp.md",
                "Age Decomposition: Dependency Ratios → Trilemma Indices")


# ── Main ─────────────────────────────────────────────────────────────

def main():
    print("=" * 70)
    print("PHASE 2: TRILEMMA INDEX REGRESSIONS")
    print("=" * 70)

    df = pd.read_csv(DATA / "trilemma_panel.csv")
    print(f"Panel: {len(df)} obs, {df['iso3'].nunique()} countries")
    print(f"Years: {df['year'].min()}–{df['year'].max()}")

    # Summary of trilemma indices
    for idx in ['mi_index', 'ers_index', 'fo_index']:
        if idx in df.columns:
            print(f"  {idx}: mean={df[idx].mean():.3f}, "
                  f"std={df[idx].std():.3f}, "
                  f"N non-null={df[idx].notna().sum()}")

    # 1. Main regressions
    trilemma_index_regressions(df)

    # 2. OECD subsample
    oecd_subsample(df)

    # 3. Age decomposition
    age_decomposition(df)

    print("\n" + "=" * 70)
    print("PHASE 2 COMPLETE")
    print("=" * 70)


if __name__ == '__main__':
    main()
